package cn.qiguai.sphapi.utils;

import cn.qiguai.sphapi.domain.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.JWTVerifier;

import java.util.Calendar;

public class JWTUtils {
	private static final String sign = "1234567890p[]l;'";

	/**
	 * 获取token
	 * @param u 用户数据
	 * @return token
	 */
	public static String getToken(User u) {
		Calendar instance = Calendar.getInstance();

		if (u.isAutoLogin()) { //自动登录
			//令牌过期时间7天
			instance.add(Calendar.DATE, 7);
		} else {
			//令牌过期时间2小时
			instance.add(Calendar.HOUR_OF_DAY, 2);
		}

		JWTCreator.Builder builder = JWT.create();
		builder.withClaim("userId", u.getId())
				.withClaim("phoneNumber", u.getPhoneNumber());

		return builder.withExpiresAt(instance.getTime())
				.sign(Algorithm.HMAC256(sign));
	}

	/**
	 * 验证token的合法性
	 * @param token token
	 * @return true：合法 false：不合法
	 */
	public static boolean verify(String token) {
		try {
			JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
			build.verify(token);
		} catch (Exception e) {
			return false;
		}

		return true;
	}
}
